package com.lmx.persistence.service;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.collect.Maps;
import com.lmx.common.constants.CommonConstants;
import com.lmx.common.util.CommonUtil;
import com.lmx.persistence.service.common.BaseCrudServiceImpl;
import com.lmx.repoDomain.exception.BusinessException;
import com.lmx.repoDomain.tmodel.ActivityOrder;
import com.lmx.repoDomain.tmodel.Dicttype;

/**
 * activityOrder service
 *
 * @author ytche
 * @date 2017年5月3日
 *
 */
@Service(value = "ActivityOrderService")
public class ActivityOrderServiceImpl extends
		BaseCrudServiceImpl<ActivityOrder> implements ActivityOrderService {
	private Log logger = LogFactory.getLog(this.getClass());

	@PersistenceContext
	private EntityManager em;

	@Autowired
	private GenericService<ActivityOrder> dslJpaService;

	@Override
	public ActivityOrder dealNewEntity(final ActivityOrder entity) {
		ActivityOrder rtn = new ActivityOrder();
		BeanUtils.copyProperties(entity, rtn);
		rtn.setActivityTime(this.getLastSecondOfDay(new Date(), entity
				.getActivityPlan().getDay()));
		return rtn;
	}

	@Override
	public void checkRepeat(ActivityOrder entity) {
		if (entity.getId() != null) {
			return;
		}
		Map<String, Object> map = Maps.newHashMap();
		map.put("customer.id", entity.getCustomer().getId());
		map.put("activityPlan.id", entity.getActivityPlan().getId());
		map.put("delStatus", CommonConstants.DEL_STATUS_NO_0);
		List<ActivityOrder> activityOrders = super.find(map);
		if (activityOrders != null && activityOrders.size() > 0) {
			throw new BusinessException(null,
					CommonConstants.ACTIVITY_ERROR_CODE.INFO_REPEAT.lable(),
					"信息重复");
		}

	}

	/**
	 * 获取date 下一周周 周*的最后一秒时间
	 *
	 * @author ytche
	 * @param date
	 * @param day
	 * @return
	 * @date 2017年5月3日 上午10:26:33
	 */
	private Integer getLastSecondOfDay(Date date, Dicttype day) {
		DateTime datetime = new DateTime(date);
		Integer activityDay = 0;
		switch (day.getTypecode()) {
		case "week1":
			activityDay = 1;
			break;
		case "week2":
			activityDay = 2;
			break;
		case "week3":
			activityDay = 3;
			break;
		case "week4":
			activityDay = 4;
			break;
		case "week5":
			activityDay = 5;
			break;
		case "week6":
			activityDay = 6;
			break;
		case "week7":
			activityDay = 7;
			break;
		default:
			break;
		}
		// 计算距离下周*的间隔天数
		activityDay += (7 - datetime.getDayOfWeek());
		Long timeNum = CommonUtil.getLastSecondOfDay(datetime.plusDays(
				activityDay).toDate());
		// 时间戳入库时候精确到秒
		return (int) (timeNum / 1000);
	}

}
